<template>
  <el-dialog :title="id ? 'Edit' : 'Insert'" :before-close="onClose">
    <el-form :model="attrForm" label-width="auto" :rules="attrFormRules" ref="attrFormCpt">
      <el-form-item prop="rule_name" label="Name">
        <el-input v-model="attrForm.rule_name"></el-input>
      </el-form-item>
      <el-form-item label="Attr" prop="spec">
        <Dragger v-model="multiAttrList" handle=".handler">
          <div v-for="item in multiAttrList" class="multi-attr-list" :key="item.label">
            <el-icon
              :size="16"
              style="margin-right: var(--space-small); cursor: move"
              class="handler"
            >
              <Sort />
            </el-icon>
            <el-input size="mini" style="width: 100px" v-model="item.label">
              {{
                item.label
              }}
            </el-input>
            <span style="margin: 0 var(--space-tiny)">：</span>
            <Dragger v-model="item.value">
              <el-tag
                closable
                size="medium"
                style="margin: 0 var(--space-small) 0 0"
                v-for="attr in item.value"
                :key="attr"
                @close="handleRemoveAttrValue(item, attr)"
              >{{ attr }}</el-tag>
            </Dragger>
            <el-input
              size="mini"
              style="width: 160px"
              v-model="item.inputValue"
              @keydown.enter.prevent="handleInsertAttrValue(item)"
            >
              <template #append>
                <el-button @click="handleInsertAttrValue(item)">+</el-button>
              </template>
            </el-input>
            <el-button
              size="mini"
              type="danger"
              style="margin-left: auto"
              @click="handleRemoveAttr(item)"
            >删除</el-button>
          </div>
        </Dragger>
        <div class="multi-attr-list">
          <el-input
            size="mini"
            v-model="newAttrName"
            style="margin-right: var(--space-small)"
            placeholder="输入规格名称"
          ></el-input>
          <el-button
            size="mini"
            type="primary"
            style="margin-left: auto"
            :disabled="!newAttrName"
            @click="handleInsertNewAttr"
          >添加</el-button>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="handleSubmit">Submit</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import { getProductAttrInfo, submitProductAttr } from '@/api/product'
import Dragger from '@/components/dragger/index.vue'
import { ElMessage } from 'element-plus'
import { Sort } from '@element-plus/icons'

interface PropsType {
  id: number;
}

const props = defineProps<PropsType>()


const attrForm = ref<ProductAttrInfoType>({
  rule_name: '',
  spec: [],
})

const attrFormRules = ref({
  rule_name: [
    { required: true, message: '请输入规格名称', },
  ],
  spec: [
    { required: true, message: '请输入规格值', trigger: 'change' },
  ],
})

watch(
  () => props.id,
  val => {
    val && getProductAttrInfo(val).then(res => {
      attrForm.value.rule_name = res.info.rule_name
      multiAttrList.value = res.info.spec.map(item => {
        return {
          label: item.value,
          value: item.detail,
          inputValue: '',
        }
      })
    })
  })

const newAttrName = ref('')

function handleInsertNewAttr() {
  multiAttrList.value.push({
    label: newAttrName.value,
    value: [],
    inputValue: '',
  })
  newAttrName.value = ''
}

function handleRemoveAttr(item: ProductAttrLocalType) {

}

const multiAttrList = ref<{
  label: string,
  value: string[],
  inputValue: string,
}[]>([])

function handleInsertAttrValue(item: ProductAttrLocalType) {
  if (item.inputValue === '') {
    return
  }

  if (item.value.find(val => val === item.inputValue)) {
    ElMessage.error(`${item.inputValue} 已存在`)
    return
  }

  item.value.push(item.inputValue)
  item.inputValue = ''
}

function handleRemoveAttrValue(item: ProductAttrLocalType, attr: string) {
  item.value = item.value.filter((a: string) => a !== attr)
}

interface ProductAttrLocalType {
  label: string
  value: string[]
  inputValue: string
}

const attrFormCpt = ref(null)

const emits = defineEmits(['update:modelValue', 'submit'])

function handleSubmit() {
  attrForm.value.spec = multiAttrList.value.map(item => {
    return {
      value: item.label,
      detail: item.value,
    }
  })

  const form = attrFormCpt.value as any

  form.validate((valid: Boolean) => {
    if (valid) {
      submitProductAttr(attrForm.value, props.id).then(() => {
        ElMessage.success('保存成功')
        emits('submit')
        onClose()
      })
    }
  })
}

function onClose() {
  const form = attrFormCpt.value as any
  form.resetFields()
  nextTick(() => {
    form.clearValidate()
    multiAttrList.value = []
    emits('update:modelValue', false)
  })
}
</script>